﻿using System;
using System.Globalization;

namespace SecurityModule
{
    //Courtesy: Aswath Krishnan
    //https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array

    public static class StringExtensions
    {
        public static byte[] FromHexToByteArray(this string hexString)
        {
            if (hexString.Length % 2 != 0)
            {
                //throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));

                hexString = "0" + hexString;
            }

            var hexAsBytes = new byte[hexString.Length / 2];
            for (var index = 0; index < hexAsBytes.Length; index++)
            {
                var byteValue = hexString.Substring(index * 2, 2);
                hexAsBytes[index] = Byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            }

            return hexAsBytes;
        }

        public static string ByteArrayToString(this byte[] ba)
        {
            var hex = BitConverter.ToString(ba).ToUpperInvariant();
            return hex.Replace("-", "");
        }
    }
}
